package com.douqu.game.core.entity.db;

import com.bean.core.buffer.ByteBuffer;
import com.douqu.game.core.factory.ConstantFactory;
import com.douqu.game.core.factory.DataFactory;
import com.douqu.game.core.util.CoreUtils;

/**
 * @author: Gavin.
 * Description:
 * Date: 2018/2/11 0011 上午 10:18
 * Huan Yu Copyright (c) 2017 All Rights Reserved.
 */
public class LotteryGoldSingleDB extends LotteryDB {
    public LotteryGoldSingleDB(int dataKey) {
        super(dataKey);
    }

    public LotteryGoldSingleDB(int dataKey, int id) {
        super(dataKey,id);
        freeCount = getConfig().freeCount;
    }

    /**最后一次抽奖时间*/
    public long lastUpdateTime;

    /**
     * 免费次数
     * */
    public int freeCount;



    @Override
    public void reset() {
        freeCount = getConfig().freeCount;
        lastUpdateTime = 0;
    }


    @Override
    public int init() {
        return freeCount = getConfig().freeCount;
    }

    @Override
    public void loadFrom(ByteBuffer buffer)
    {
        super.loadFrom(buffer);
        long updateTime = buffer.readInt();
        lastUpdateTime = updateTime*1000;
        freeCount = buffer.readByte();
    }

    @Override
    public void writeTo(ByteBuffer buffer)
    {
        super.writeTo(buffer);

        int updateTime = (int) (lastUpdateTime /1000);
        buffer.writeInt(updateTime);
        buffer.writeByte(freeCount);
    }


    @Override
    public boolean isTodayByOffset()
    {
        return lastUpdateTime <= 0 || CoreUtils.isTodayByOffset(lastUpdateTime, DataFactory.currentTime, ConstantFactory.DEFAULT_RESET_FRESH_TIMES_HOUR);
    }

    @Override
    public boolean checkCDTime() {
        return lastUpdateTime == 0  || DataFactory.currentTime - lastUpdateTime >= getConfig().cdTime;
    }

    @Override
    public boolean checkFreeCount() {
        if(freeCount > 0){
            if(checkCDTime()){
                freeCount--;
                return true;
            }else{
                return false;
            }

        }
        return false;
    }

    @Override
    public int getFreeCount() {
        return freeCount;
    }

    @Override
    public int getCDTime() {
        if(lastUpdateTime == 0)
            return 0;

        int tempTime = (int) (DataFactory.currentTime - lastUpdateTime);

        return tempTime > getConfig().cdTime ? 0 : getConfig().cdTime - tempTime;
    }

    @Override
    public long getLastUpdateTime() {
        return lastUpdateTime;
    }

    @Override
    public void setCdTime() {
        lastUpdateTime = DataFactory.currentTime;
    }
}
